package com.moorror.codegenvel.view.window.codegen.view;


import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBTabbedPane;
import com.moorror.codegenvel.db.sqlite.entity.CodeGenTemplate;
import com.moorror.codegenvel.domain.bean.savefile.SaveFileDesc;
import com.moorror.codegenvel.tab.TabJsonWrap;
import com.moorror.codegenvel.tab.TabWrapEditor;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;

/**
 * @Author jiyanghuang
 * @Date 2025/8/15 22:40
 */
public class CodeGenTemplatePanel extends JPanel {

    private Project project;

    private JTabbedPane tabbedPane;

    private TabWrapTabCodeGenTemplateKeyFields keyFields;

    private TabJsonWrap templateJsonValue;

    private TabJsonWrap tabJsonWrap;

    private TabWrapEditor tabWrapEditor;

    private CodeGenTemplate codeGenTemplate;

    private TabWrapEditor tabWrapEditorResult;


    public CodeGenTemplatePanel(Project project, CodeGenTemplate codeGenTemplate) {
        this.project = project;
        this.codeGenTemplate = codeGenTemplate;
        initView();
    }

    private void initView() {
        setLayout(new BorderLayout(0, 0));
        tabbedPane = new JTabbedPane(JBTabbedPane.TOP);
        tabWrapEditor = new TabWrapEditor(project, 0, "VelocityContent", tabbedPane, codeGenTemplate.getContent(), false);
        keyFields = new TabWrapTabCodeGenTemplateKeyFields(project, 1, "KeyFields", tabbedPane, new TabCodeGenTemplateKeyFields(this.project, this.codeGenTemplate));
        tabJsonWrap = new TabJsonWrap(project, 2, "VelocityContext", tabbedPane, codeGenTemplate.getContent(), false);
        add(tabbedPane, BorderLayout.CENTER);
    }

    public void replaceResult(SaveFileDesc saveFileDesc) {
        if (StringUtils.isNotEmpty(saveFileDesc.getContent()) && StringUtils.isNotEmpty(saveFileDesc.getExtension()) && StringUtils.isNotEmpty(saveFileDesc.getFileName())) {
            if (null != tabWrapEditorResult) {
                tabWrapEditorResult.fillSource(saveFileDesc.getContent());
            } else {
                tabWrapEditorResult = new TabWrapEditor(project, 3, saveFileDesc.getFileName(), tabbedPane, saveFileDesc.getExtension(), saveFileDesc.getContent(), true);
            }
        } else if (StringUtils.isNotEmpty(saveFileDesc.getContent())) {
            if (null != tabWrapEditorResult) {
                tabWrapEditorResult.fillSource(saveFileDesc.getContent());
            } else {
                tabWrapEditorResult = new TabWrapEditor(project, 3, "CodeSnippet", tabbedPane, "java", saveFileDesc.getContent(), true);
            }
        }
    }

    public void fetchValue(){
        codeGenTemplate.setContent(tabWrapEditor.text());
        codeGenTemplate.setJsonContext(tabJsonWrap.text());
        keyFields.fetchValue();
    }
}
